package com.isoft.c2team3service2.config;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.isoft.c2team3service2.entity.UserDTO;
import com.isoft.c2team3service2.mapper.PersonMapper;
import com.isoft.c2team3service2.util.UserHolder;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Collections;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.isoft.c2team3service2.util.RedisConstants.USER_LOGIN_KEY;

/**
 * @author 蓝莓
 * @date 2025/6/18 11:43
 */
public class RefreshTokenInterceptor implements HandlerInterceptor {
//    //这个对象是我们自己new出来的，并没有交给spring，无@Commonpent注解，所以我们自己来构造器注入
    private StringRedisTemplate stringRedisTemplate;

    private PersonMapper personMapper;

    public  RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate, PersonMapper personMapper) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.personMapper = personMapper;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        System.out.println("接收到的 Token：" + token);
        // 在preHandle方法开始处添加详细日志
        System.out.println("请求URI: " + request.getRequestURI());
        System.out.println("完整请求头: " + Collections.list(request.getHeaderNames()));
//        if (StrUtil.isBlank(token)) {
//            System.out.println("Authorization头不存在或为空refresh");
//            return true;
//        }
//
//// 更健壮的Bearer token处理
//        if (token.startsWith("Bearer ")) {
//            token = token.substring(7);
//        } else {
//            System.out.println("Token格式不正确，缺少Bearer前缀refresh");
//            // 根据您的需求决定是否放行
//            return true;
//        }
//
//        if (StrUtil.isBlank(token)) {
//            System.out.println("Token is blankrefresh");
//            return true;
//        }

//         去掉 Bearer 前缀
        token = token.replace("Bearer ", "");

        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(USER_LOGIN_KEY + token);
        if (userMap.isEmpty()) {
            System.out.println("User info not found in Redisrefresh");
            return true;
        }

        UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);
        System.out.println("UserDTO from Redis:refresh " + userDTO);
        System.out.println("UserHolder 已保存用户：refresh" + UserHolder.getUser());

        UserHolder.saveUser(userDTO);
        stringRedisTemplate.expire(USER_LOGIN_KEY + token, 60, TimeUnit.MINUTES);
        return true;



    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
    }
}
